//
//  DnpLocationTracking.m
//  dnp_plugin
//
//

#import "DnpLocationTracking.h"

@interface DnpLocationTracking()
@property (strong, nonatomic) CLLocationManager *geoLocationManager;
@end

@implementation DnpLocationTracking

- (void)beginUpdates {
    [self endUpdates];
    [self.geoLocationManager startUpdatingLocation];
}

- (void)endUpdates {
    [self.geoLocationManager stopUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [manager stopUpdatingLocation];
        
    CLLocation *location = [locations firstObject];
    
    CLLocationCoordinate2D coordinate = location.coordinate;
    
    NSString *longitude = coordinate.longitude == 0 ? @"0" : [NSString stringWithFormat:@"%.6f", coordinate.longitude];
    NSString *latitude = coordinate.latitude == 0 ? @"0" : [NSString stringWithFormat:@"%.6f", coordinate.latitude];
    
    NSDictionary *locationMap = @{
        @"longitude": longitude,
        @"latitude": latitude,
    };
    
    if (self.locationHander) {
        self.locationHander(locationMap);
    }
}

- (CLLocationManager *)geoLocationManager {
    if (!_geoLocationManager) {
        _geoLocationManager = [[CLLocationManager alloc] init];
        _geoLocationManager.delegate = self;
        _geoLocationManager.distanceFilter = 0;
        _geoLocationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [_geoLocationManager requestWhenInUseAuthorization];
    }
    return _geoLocationManager;
}


@end
